<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="货件编号" prop="shipmentConfirmationId">
              <el-input v-model="queryParams.shipmentConfirmationId" placeholder="请输入货件编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工厂名称" prop="factory">
              <el-input v-model="queryParams.factory" placeholder="请输入工厂名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="员工" prop="employee">
              <el-input v-model="queryParams.employee" placeholder="请输入员工" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="上传时间" prop="uploadTime">
              <el-date-picker clearable
                v-model="queryParams.uploadTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择上传时间"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="materialList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="" align="center" prop="id" />
        <el-table-column label="货件编号" align="center" prop="shipmentConfirmationId" />
        <el-table-column label="工厂名称" align="center" prop="factory" />
        <el-table-column label="外箱标和唛头" align="center" width="150">
          <template #default="scope">
            <div class="image-container">
              <template v-if="scope.row.outerBoxAndMarkList && scope.row.outerBoxAndMarkList.length > 0">
                <template v-for="(item, index) in scope.row.outerBoxAndMarkList.slice(0, 2)" :key="item.id">
                  <el-image 
                    :src="item.url" 
                    :preview-src-list="scope.row.outerBoxAndMarkList.map(i => i.url)"
                    :initial-index="index"
                    preview-teleported
                    fit="cover"
                    class="image-thumb"
                    :title="`状态: ${getStatusText(item.status)}${item.status === 2 ? ', 原因: ' + item.cause : ''}`"
                  />
                </template>
                <el-button v-if="scope.row.outerBoxAndMarkList.length > 2" link type="primary" @click="showMoreImages(scope.row.outerBoxAndMarkList, '外箱标和唛头')" class="more-button">+{{ scope.row.outerBoxAndMarkList.length - 2 }}</el-button>
              </template>
              <span v-else>暂无材料</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品标" align="center" width="150">
          <template #default="scope">
            <div class="image-container">
              <template v-if="scope.row.productLabelList && scope.row.productLabelList.length > 0">
                <template v-for="(item, index) in scope.row.productLabelList.slice(0, 2)" :key="item.id">
                  <el-image 
                    :src="item.url" 
                    :preview-src-list="scope.row.productLabelList.map(i => i.url)"
                    :initial-index="index"
                    preview-teleported
                    fit="cover"
                    class="image-thumb"
                    :title="`状态: ${getStatusText(item.status)}${item.status === 2 ? ', 原因: ' + item.cause : ''}`"
                  />
                </template>
                <el-button v-if="scope.row.productLabelList.length > 2" link type="primary" @click="showMoreImages(scope.row.productLabelList, '产品标')" class="more-button">+{{ scope.row.productLabelList.length - 2 }}</el-button>
              </template>
              <span v-else>暂无材料</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="员工" align="center" prop="employee" />
        <el-table-column label="发货时间" align="center" prop="shipmentsTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.shipmentsTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="下载压缩包" placement="top"> 
              <el-button link type="primary" icon="Download" @click="handleDownloadBatch(scope.row.id)" v-hasPermi="['ymxbh:shipment:download']"></el-button>
              <!-- <el-button link type="primary" icon="Download" @click="handleDownloadBatch(1)" v-hasPermi="['ymxbh:shipment:download']"></el-button> -->
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    
    <!-- 图片预览弹窗 -->
    <el-dialog v-model="imageDialog.visible" :title="imageDialog.title" width="600px" append-to-body>
      <div class="image-gallery">
        <el-image 
          v-for="(item, index) in imageDialog.images" 
          :key="item.id"
          :src="item.url" 
          :preview-src-list="imageDialog.images.map(i => i.url)"
          :initial-index="index"
          preview-teleported
          fit="cover"
          class="gallery-image"
          :title="`状态: ${getStatusText(item.status)}${item.status === 2 ? ', 原因: ' + item.cause : ''}`"
        />
      </div>
    </el-dialog>

    <!-- 添加或修改材料管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="materialFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="id">
          <el-input v-model="form.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="货件编号" prop="shipmentConfirmationId">
          <el-input v-model="form.shipmentConfirmationId" placeholder="请输入货件编号" />
        </el-form-item>
        <el-form-item label="工厂名称" prop="factory">
          <el-input v-model="form.factory" placeholder="请输入工厂名称" />
        </el-form-item>
        <el-form-item label="员工" prop="employee">
          <el-input v-model="form.employee" placeholder="请输入员工" />
        </el-form-item>
        <el-form-item label="发货时间" prop="shipmentsTime">
          <el-date-picker clearable
            v-model="form.shipmentsTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上传时间" prop="uploadTime">
          <el-date-picker clearable
            v-model="form.uploadTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择上传时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Material" lang="ts">
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, downloadBatch } from '@/api/ymxbh/material';
import { MaterialVO, MaterialQuery, MaterialForm } from '@/api/ymxbh/material/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const materialList = ref<MaterialVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const materialFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 图片预览弹窗
const imageDialog = reactive({
  visible: false,
  title: '',
  images: [] as any[]
});

const initFormData: MaterialForm = {
  id: undefined,
  shipmentConfirmationId: undefined,
  factory: undefined,
  employee: undefined,
  shipmentsTime: undefined,
  uploadTime: undefined,
}
const data = reactive<PageData<MaterialForm, MaterialQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shipmentConfirmationId: undefined,
    factory: undefined,
    employee: undefined,
    shipmentsTime: undefined,
    uploadTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    shipmentConfirmationId: [
      { required: true, message: "货件编号不能为空", trigger: "blur" }
    ],
    factory: [
      { required: true, message: "工厂名称不能为空", trigger: "blur" }
    ],
    employee: [
      { required: true, message: "员工不能为空", trigger: "blur" }
    ],
    shipmentsTime: [
      { required: true, message: "发货时间不能为空", trigger: "blur" }
    ],
    uploadTime: [
      { required: true, message: "上传时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待查看';
    case 1: return '确认';
    case 2: return '驳回';
    default: return '未知';
  }
};

// 下载压缩包
const handleDownloadBatch = (id: string | number) => {
  downloadBatch(id);
};

/** 查询材料管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMaterial(queryParams.value);
  materialList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  materialFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaterialVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加材料管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MaterialVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getMaterial(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改材料管理";
}

/** 提交按钮 */
const submitForm = () => {
  materialFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMaterial(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addMaterial(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除材料管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delMaterial(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('ymxbh/material/export', {
    ...queryParams.value
  }, `material_${new Date().getTime()}.xlsx`)
}

// 显示更多图片
const showMoreImages = (images: any[], title: string) => {
  imageDialog.images = images;
  imageDialog.title = title;
  imageDialog.visible = true;
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  min-height: 50px;
}

.image-thumb {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.more-button {
  height: 40px;
  padding: 0 8px;
  font-size: 12px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.gallery-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}
</style>